package com.dddd.blog.bloguser.controller;


import com.dddd.blog.api.user.pojo.User;
import com.dddd.blog.blogcommon.constant.ResultCode;
import com.dddd.blog.blogcommon.controller.BaseController;
import com.dddd.blog.blogcommon.pojo.Result;
import com.dddd.blog.blogcommon.pojo.vo.UserLoginVO;
import com.dddd.blog.blogcommon.utils.JwtUtils;
import com.dddd.blog.blogcommon.utils.PasswordUtils;
import com.dddd.blog.blogcommon.utils.ResultUtils;
import com.dddd.blog.bloguser.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 用户登录 前端控制器
 * </p>
 *
 * @author dddd
 * @since 2022-02-27
 */
@RestController
public class LoginController extends BaseController {

    private static final long EXPIREMILLS = 7 * 24 * 60 * 60 * 1000;

    @Autowired
    private IUserService userService;

    @PostMapping("/login")
    public Result login(@RequestBody UserLoginVO vo){

        Result result = ResultUtils.success();

        if(vo!=null){
            User temp = userService.getUserByName(vo.getUsername());
            if(temp == null){
                return result.setResult(ResultCode.OBJECT_NOT_EXIST);
            }
            String passwordEncode = temp.getPassword();
            getLogger().warn("用户加密密码",passwordEncode);
            boolean correct = PasswordUtils.isCorrectPassword(vo.getPassword(), temp.getSalt(), passwordEncode);
            if(correct){
                //密码正确，创建token
                String token = JwtUtils.createToken(vo.getUsername(), EXPIREMILLS);

                return result.setResult(ResultCode.SUCCESS,token);
            }
            else{
                return result.setResult(ResultCode.PASSWORD_INCORRECT);
            }
        }
        return result.setResult(ResultCode.PARAMS_BLANK);
    }
}
